<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="采购时间" prop="purchaseDate">
                        <el-date-picker
                            v-model="entityObj.purchaseDate"
                            :default-time="defaultTime"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入采购时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="采购类型">
                        <el-select
                            placeholder="---请选择采购类型---"
                            v-model="entityObj.purchaseType"
                            style="width: 300px"
                        >
                            <el-option label="集采中心自采" value=1 />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="采购单位" prop="storeId">
                        <el-tooltip placement="top" style="width: 80%">
                            <template #content>
                                联系人: {{entityObj.purchaseRealName}}
                                <br />
                                联系电话:{{entityObj.purchaseMobile}}
                                <br />
                                收货地址:{{entityObj.purchaseAddress}}
                            </template>
                            <el-input
                                disabled
                                v-model="entityObj.purchaseUnityName"
                                style="width: 100%"
                            />
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="供应商" prop="supplierId">
                        <sc-supplier-select
                            ref="supplierSelect"
                            :props="supplierProps"
                            :selectKeyValue="'supplierId'"
                            :multiple="false"
                            v-model="entityObj.suppliers"
                            @fatherMethod="supplierSelectProcess"
                        ></sc-supplier-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="采购清单" prop="purchaseOrderItems">
                        <el-button size="small" @click="addMaterial()">新增物料</el-button>
                        <!-- <el-button
                            size="small"
                            @click="addApplyOrder()"
                            style="margin-left: 20px;"
                        >从历史要货记录中复购</el-button>-->
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px">
                        <el-form inline label-width="49px" style="margin-top: 5px">
                            <el-form-item label="物料编号" label-width="80px">
                                <el-input
                                    placeholder="---请输入编号---"
                                    v-model="queryList.materialCode"
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-form-item label="物料名称" label-width="80px">
                                <el-input
                                    placeholder="---请输入名称---"
                                    v-model="queryList.materialName"
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-form-item label="物料分类" label-width="80px">
                                <el-tree-select
                                    placeholder="---请选择物料分类---"
                                    collapse-tags
                                    collapse-tags-tooltip
                                    v-model="queryList.materialTypeIds"
                                    :props="{ label: 'label', value:'value',children: 'children' }"
                                    :data="materialTypeTree"
                                    multiple
                                    :render-after-expand="false"
                                    show-checkbox
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-button
                                :icon="Search"
                                 
                                type="primary"
                                @click="handleSearch"
                            >查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                            <el-form inline label-width="49px" style="margin-top: 5px"></el-form>
                        </el-form>
                        <el-table :data="itemsData" border style="width: 100%" show-summary>
                            <!-- <el-table-column label="物料编码" min-width="130">
                                <template #default="scope">{{scope.row.materialCode}}</template>
                            </el-table-column> -->
                            <el-table-column label="物料名称" min-width="130">
                                <template #default="scope">
                                    <el-tooltip placement="top" style="width: 80%">
                                        <template #content>
                                            {{scope.row.materialCode}}
                                        </template>
                                        {{scope.row.materialName}}
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格" min-width="120">
                                <template #default="scope">{{scope.row.materialSpecs}}</template>
                            </el-table-column>
                            <!-- <el-table-column label="物料类别" min-width="130">
                                <template #default="scope">{{scope.row.materialTypeName}}</template>
                            </el-table-column> -->
                            <el-table-column label="单位" min-width="95">
                                <template #default="scope">{{scope.row.unitName}}</template>
                            </el-table-column>
                            <el-table-column label="采购单价" min-width="110">
                                <template #default="scope">{{scope.row.price}}</template>
                            </el-table-column>
                            <el-table-column label="数量" min-width="130" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" min-width="130" prop="totalAmount"></el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" min-width="120">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="deleteRow(scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="附件">
                        <sc-upload-file
                            v-model="entityObj.applyFile"
                            :objName="'Supply/ApplyOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="下单备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <!-- <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(3)"
            >暂 存</el-button>-->
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(4)"
            >保 存</el-button>
        </template>

        <template>
            <full-screen-dialog
                v-model="materialState"
                title="选择商品"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <sc-material-choice
                        ref="scMaterialChoice"
                        :queryType="'purchase-protocol/item-pages'"
                        :queryList="{supplierId: entityObj.supplierId}"
                    ></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </full-screen-dialog>
        </template>

        <template>
            <full-screen-dialog
                v-model="applyOrderState"
                title="复购"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <sc-apply-order-choice ref="scApplyOrderChoice"></sc-apply-order-choice>
                </el-row>
                <template #footer>
                    <el-button @click="applyOrderState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setApplyOrderChoice">确定</el-button>
                </template>
            </full-screen-dialog>
        </template>
    </full-screen-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                purchaseOrderItems: [],
            },
            orgType: 2,
            materialState: false,
            applyOrderState: false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                purchaseDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                supplierId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                purchaseOrderItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
            },
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            storeProps: {
                label: "storeName",
                value: "storeId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseUnity: [],
            itemsData: [],
        };
    },
    computed: {
        totalAmount() {
            let materialFee = 0;
            this.entityObj.purchaseOrderItems.map((p) => {
                p.totalAmount = p.price * p.qty;
                materialFee += p.totalAmount;
            });
            const totalAmount = materialFee;
            return totalAmount;
        },
    },
    methods: {
        //显示=
        async open(mode = "Add") {
            //获取当前店铺信息
            if (mode == "Add" && this.orgType == 2) {
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    "store/current"
                );
                if (returnValue.status == 200) {
                    this.entityObj.storeName = returnValue.response.storeName;
                    this.entityObj.storeId = returnValue.response.storeId;
                    this.entityObj.realName = returnValue.response.realName;
                    this.entityObj.mobile = returnValue.response.mobile;
                    this.entityObj.address = returnValue.response.address;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            }
            this.mode = mode;
            this.visible = true;
            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //表单提交方法
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "purchase-order/self-create"
                                    : "purchase-order/self-update",
                                { ...this.entityObj, status: status }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            //this.entityObj = data;
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            if(this.orgType==1){
                //采购单位列表
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    "purchase-unity/current"
                );
                if (returnValue.status == 200) {
                    this.optionsPurchaseUnity = returnValue.response;
                    this.entityObj.purchaseUnityId =
                        returnValue.response.purchaseUnityId;
                    this.entityObj.purchaseUnityName =
                        returnValue.response.purchaseUnityName;
                    this.entityObj.purchaseRealName = returnValue.response.realName;
                    this.entityObj.purchaseMobile = returnValue.response.mobile;
                    this.entityObj.purchaseAddress = returnValue.response.address;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            }
        },
        async supplierSelectProcess(rowData) {
            this.entityObj.supplier = {
                supplierId: rowData.supplierId,
                supplierName: rowData.supplierName,
            };
            this.entityObj.supplierId=rowData.supplierId
        },
        addMaterial() {
            if (!this.entityObj.supplierId) {
                this.$message.error("请先选择供应商");
                return;
            }
            this.materialState = true;
            this.$nextTick(() => {
                this.$refs.scMaterialChoice.opBindData();
            });
        },
        deleteRow(index) {
            this.entityObj.purchaseOrderItems.splice(index, 1);
        },
        handleSearch() {
            this.itemsData = this.entityObj.purchaseOrderItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                this.itemsData = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
        },
        setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            materials.map((p) => {
                this.entityObj.purchaseOrderItems.push({
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    unitCode:p.unitCode,
                    unitName:p.unitName,
                    qty: 0,
                    totalAmount: 0,
                    remarks: "",
                    materialItemId: p.materialItemId,
                    price: p.price,
                });
            });
            this.materialState = false;
            this.queryList = {};
            this.handleSearch();
        },
        addApplyOrder() {
            this.applyOrderState = true;
        },
        async setApplyOrderChoice() {
            let applyOrders = this.$refs.scApplyOrderChoice.selectionRows;
            let materialIds = [];
            applyOrders.map((t) =>
                t.purchaseOrderItems.map((p) => {
                    materialIds.push(p.materialId);
                })
            );
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "delivery-protocol/material-pages",
                { pageIndex: 1, pageSize: 9999, materialIds: materialIds }
            );
            if (returnValue.status == 200) {
                const materials = returnValue.response.data;
                applyOrders.map((t) =>
                    t.purchaseOrderItems.map((p) => {
                        const material = materials.find(
                            (t) => t.materialId == p.materialId
                        );

                        this.entityObj.purchaseOrderItems.push({
                            materialId: material.materialId,
                            materialCode: material.materialCode,
                            materialName: material.materialName,
                            materialSpecs: material.materialSpecs,
                            materialTypeId: material.materialTypeId,
                            materialTypeName: material.materialTypeName,
                            //price: p.price,
                            qty: p.qty,
                            //totalAmount: p.totalAmount,
                            remarks: p.remarks,
                            materialItemId: p.materialItemId,
                            materialItems: material.materialItems,
                        });
                    })
                );
                console.log(1111);
                this.applyOrderState = false;
                this.queryList = {};
                this.handleSearch();
            }
        },
        purchaseUnityChange(value) {
            this.entityObj.purchaseRealName = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).realName;
            this.entityObj.purchaseMobile = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).mobile;
        },
        storeSelectProcess(rowData) {
            console.log(rowData);
            this.entityObj.store = rowData;
            this.entityObj.storeName = rowData.storeName;
            this.entityObj.storeId = rowData.storeId;
            this.entityObj.realName = rowData.realName;
            this.entityObj.mobile = rowData.mobile;
            this.entityObj.address = rowData.address;
        },
        formatDate(date, type = 0) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return type == 0
                ? `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
                : `${year}-${month}-${day}`;
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        this.entityObj.applyName = tool.data.get("USER_INFO").Name;
        this.entityObj.applyDate = this.formatDate(new Date(), 1);
        this.entityObj.createTime = this.formatDate(new Date());

        await this.initOptions();
    },
};
</script>

<style></style>
